package org.example.top40;

public class main36 {
    //删除链表的倒数第n个节点
    //输入：head = [1,2,3,4,5], n = 2
    //输出：[1,2,3,5]
    //思路：快慢指针 fast for先行 如过删除的是第一个fast==null 直接head.next
    //最后是slow.next=slow.next.next
    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        ListNode node1 = new ListNode(2);
        ListNode node2 = new ListNode(3);
        ListNode node3 = new ListNode(4);
        ListNode node4 = new ListNode(5);
        head.next=node1;
        node1.next=node2;
        node2.next=node3;
        node3.next=node4;
        int n=2;
        ListNode node=reverseLastN(head,n);
        System.out.println(node.val);
    }

    private static ListNode reverseLastN(ListNode head,int n) {
        ListNode slow=head;
        ListNode fast=head;
        for (int i = 0; i < n; i++) {
            fast=fast.next;
            if(fast==null){
                return head.next;
            }
        }
        while (fast!=null&&fast.next!=null){
            slow=slow.next;
            fast=fast.next;
        }
        slow.next=slow.next.next;
        return head;
    }
}
